package com.changgou.order.schedul;

import com.changgou.order.pojo.OrderLog;
import com.changgou.order.service.OrderService;
import com.changgou.pay.feign.WeiXinPayFeign;
import entity.RedisConfig;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

/****
 * 防止由于网络原因没有收到支付回调，每隔5秒主动查询订单支付状态
 */
@Component
public class QueryPayStatus {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WeiXinPayFeign weiXinPayFeign;

    @Scheduled(cron = "0/5 * * * * *")
    public void queryPay() throws Exception {
        RedisConfig.convertRedisTemplate(redisTemplate);

        String orderLogId = (String) redisTemplate.boundListOps("OrderLogList").rightPop();
        if (orderLogId != null) {
            //查询日志信息
            OrderLog orderLog = (OrderLog) redisTemplate.boundHashOps("OrderLog").get(orderLogId);
            if (orderLog == null) {
                //没有支付日志则已经操作过，直接返回
                return;
            }

            //否则查询支付状态
            Result result = weiXinPayFeign.queryStatus(orderLogId);
            Map<String, String> resultMap = (Map<String, String>) result.getData();
            //网络通信标识
            String returnCode = resultMap.get("return_code");
            //业务返回代码
            String resultCode = resultMap.get("result_code");
            //交易状态
            String tradeState = resultMap.get("trade_state");
            if (returnCode.equalsIgnoreCase("success") && resultCode.equalsIgnoreCase("success")) {
                if (tradeState.equalsIgnoreCase("success")) {
                    //支付成功，修改订单状态
                    orderService.updateStatus(orderLog.getUsername(), orderLog.getOrderId(), resultMap.get("transaction_id"), orderLog);
                } else if (tradeState.equalsIgnoreCase("notpay") || tradeState.equalsIgnoreCase("userpaying")) {
                    //未支付或正在支付，则重新将订单id存入队列，后面再去查询
                    redisTemplate.boundListOps("OrderLogList").leftPush(orderLogId);
                } else {
                    //其他情况则直接取消订单，回滚库存
                    orderService.deleteOrder(orderLog);
                }
            } else {
                //查询失败，或者支付订单还未创建，重新将订单id存入队列，后面再去查询
                redisTemplate.boundListOps("OrderLogList").leftPush(orderLogId);
            }
        }
    }
}
